package cn.ulc.socket.admin.service.common.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ulc.common.constant.PubDataConstant;
import cn.ulc.common.constant.enums.ResultCode;
import cn.ulc.common.exception.PlatformException;
import cn.ulc.common.util.ConvertUtil;
import cn.ulc.common.util.JwtUtil;
import cn.ulc.socket.admin.common.BaseService;
import cn.ulc.socket.admin.model.dto.account.LoginDTO;
import cn.ulc.socket.admin.model.dto.staff.StaffDTO;
import cn.ulc.socket.admin.model.param.account.ChangePasswordParam;
import cn.ulc.socket.admin.model.param.account.LoginDetailParam;
import cn.ulc.socket.admin.service.common.AccountServ;
import cn.ulc.store.dao.CompanyDao;
import cn.ulc.store.dao.staff.StaffDao;
import cn.ulc.store.entity.Company;
import cn.ulc.store.entity.staff.Staff;
import io.jsonwebtoken.Claims;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;


@Service
@AllArgsConstructor
public class AccountServImpl extends BaseService implements AccountServ {
    private static final Log log = LogFactory.get();

    StaffDao staffDao;
    CompanyDao companyDao;

    @Override
    public LoginDTO login(LoginDetailParam param) {
        String password = ConvertUtil.toMD5(param.getPassword());
        System.out.println("=password"+password);
        Staff staff = staffDao.findByLoginNameAndPasswordAndDeleted(param.getLoginName(),password);
        if(staffDao == null){
            throw new PlatformException("用户名或密码错误！");
        }
        String token = JwtUtil.createJWT(staff.getId(),staff.getCompanyId(), PubDataConstant.LOGIN_ADMIN);
        return new LoginDTO(token);
    }

    @Override
    public StaffDTO findUserInfo(String token) {
        Claims claims = JwtUtil.parseJwtToken(token);
        Long userId = 0l;
        if(claims != null) userId = Convert.toLong(claims.get("userId"),0l);
        if(userId <= 0) throw new PlatformException(ResultCode.NO_LOGIN.getCode(),"验证用户信息失败");
        Staff entity = staffDao.findOne(userId);
        if(entity == null) throw new PlatformException(ResultCode.NO_LOGIN.getCode(),"用户不存在或已注销");
        Company company = companyDao.findOne(entity.getCompanyId());
        if(company == null) throw new PlatformException(ResultCode.NO_LOGIN.getCode(),"用户不存在或已注销");
        entity.setCompanyName(company.getName());
        entity.setCompanyLogo(company.getLogo());
        return StaffDTO.builder().model(entity).build();
    }

    @Override
    public Boolean changePassword(ChangePasswordParam param) {
        Staff loginUser = getCurrentUser();
        if(!ConvertUtil.toMD5(param.getOldPassword()).equals(loginUser.getPassword())) throw new PlatformException("原密码输入有误!");
        loginUser.setPassword(ConvertUtil.toMD5(param.getPassword()));
        setBaseInfo(loginUser);
        staffDao.save(loginUser);
        return true;
    }
}
